<template>
  <view>
    <u-navbar title="Rococo Studio" is-fixed="true" z-index="999" :is-back="false" :background="background"
      :border-bottom="false">
    </u-navbar>
    <view class="ImageBox">
      <image src='https://typora-licodeao.oss-cn-guangzhou.aliyuncs.com/typoraImg/会议.jpeg' class="topImage"></image>
    </view>
    <view class="upload" @click="chooseFile">
      <image src="https://typora-licodeao.oss-cn-guangzhou.aliyuncs.com/typoraImg/file.webp" class="img1"></image>
      <view class="textBox">
        <view class="topText">快速上传会议记录</view>
        <view class="bottomText">支持word文档 | 由记录人员上传</view>
      </view>
    </view>
    <view class="locationBox" @click="getLocation" :disabled="isSigned">
      <image src="https://typora-licodeao.oss-cn-guangzhou.aliyuncs.com/typoraImg/location.webp" class="img1"></image>
      <view class="textBox">
        <view class="topText">会议签到一触就行</view>
        <view class="bottomText">每周例会签到 | 12:40 ~ 12:50</view>
      </view>
    </view>
    <view class="upload" @click="onDuty">
      <image src="https://typora-licodeao.oss-cn-guangzhou.aliyuncs.com/typoraImg/wifi.jpg" class="img1"></image>
      <view class="textBox">
        <view class="topText">快速进行值日签到</view>
        <view class="bottomText">记录每周考勤 | 支持签到与签退</view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    formatTime,
    formatPrefixTime
  } from '../../store/formatDate/formatDate.js'
  export default {
    data() {
      return {
        background: {
          backgroundColor: '#F6F6F6'
        },
        serverUrl: this.$globalUrl,
        // 工作室坐标
        aimLocation: {
          // 纬度
          latitude: "23.432101663223868",
          // 经度
          longitude: "113.16626700583208"
        },
        userLocation: {
          // 当前定位纬度
          currentLatitude: 0,
          // 当前定位经度
          currentLongitude: 0
        },
        // 签到半径
        radius: 5,
        // 距离
        distance: 0,
        // 签到地点
        place: "",
        success: false,
        // 手机设置里的WiFi开关是否开启
        isOpenMobileWifi: false,
        // 是否值班签到
        isSuccess: false,
        // 是否值班签退
        isSignOut: false,
        // 值班签到开始时间
        signInBeginTime: "",
        // 值班签到结束时间
        signInEndTime: "",
        // 值班签退开始时间
        signOutTime: "",
        // 值班签退结束时间
        signOutEndTime: "",
        // 用户点击签到按钮的时间
        userSignTime: "",
        // 会议签到开始时间
        meetingBeginTime: "",
        // 会议签到结束时间
        meetingEndTime: "",
        // 是否签到
        isSigned: false
      }
    },
    methods: {
      async chooseFile() {
        let self = this
        await wx.chooseMessageFile({
          count: 1,
          extension: ['.doc', '.docx'],
          success(res) {
            console.log("成功选择文件", JSON.stringify(res.tempFiles), res.tempFiles)
            const tempFilePaths = res.tempFiles
            wx.uploadFile({
              url: self.$globalUrl + '/meet/analyWord',
              filePath: tempFilePaths[0].path,
              name: 'file',
              file: {
                'filePath': tempFilePaths[0]
              },
              header: {
                "Authorization": uni.getStorageSync('tokenHead') + ' ' + uni.getStorageSync('token')
              },
              success(res) {
                console.log(JSON.parse(res.data))
                let result = JSON.parse(res.data)
                if (result.code === 401) {
                  uni.showToast({
                    icon: "error",
                    title: '请先登录再上传',
                    duration: 2000
                  })
                } else if (result.status === 500) {
                  uni.showToast({
                    icon: "error",
                    title: '请选择正确的格式',
                    duration: 2000
                  })
                } else if (result.code === 200) {
                  self.$store.commit('changeContent', result.object.content)
                  self.$store.commit('changeDate', result.object.date)
                  self.$store.commit('changeLatePerson', result.object.latePerson)
                  self.$store.commit('changeLeavingPerson', result.object.leavingPerson)
                  self.$store.commit('changeHost', result.object.meetingHost)
                  self.$store.commit('changePlace', result.object.place)
                  self.$store.commit('changeRecorder', result.object.recorder)
                  self.$store.commit('changeTerm', result.object.term)
                  self.$store.commit('changeWeek', result.object.week)
                  console.log(self.$store.state.meeting)
                  let item = encodeURIComponent(JSON.stringify(result.object))
                  uni.navigateTo({
                    url: `../../subpkg/addMeeting/addMeeting?item=${item}`
                  })
                }
              }
            })
          }
        })
      },
      getLocation() {
        let that = this
        const tMap = new that.TMap({
          key: 'VEVBZ-3TQ3P-OXKDB-LP7LM-WY3SS-A3BQY'
        })
        // 用户点击签到按钮的时间
        that.userSignTime = new Date(formatTime(new Date())).getTime()
        if (that.userSignTime < that.meetingBeginTime) {
          uni.showToast({
            icon: 'error',
            title: '签到还未开始',
            duration: 2000
          })
        } else if (that.userSignTime > that.meetingEndTime) {
          uni.showToast({
            icon: 'error',
            title: '签到已结束',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: "定位中",
            icon: "loading",
            duration: 3000,
            mask: true
          })
          wx.getLocation({
            type: 'wgs84',
            isHighAccuracy: true,
            highAccuracyExpireTime: 3100,
            success(res) {
              that.userLocation.currentLatitude = res.latitude
              that.userLocation.currentLongitude = res.longitude
              that.distance = that.calculateDistance(that.aimLocation.latitude, that.aimLocation.longitude, that.userLocation.currentLatitude, that.userLocation.currentLongitude)
              console.log("计算函数返回值：", that.calculateDistance(that.aimLocation.latitude, that.aimLocation.longitude,
                that.userLocation.currentLatitude, that.userLocation.currentLongitude))
              tMap.reverseGeocoder({
                location: {
                  latitude: that.userLocation.currentLatitude,
                  longitude: that.userLocation.currentLongitude
                },
                success(res) {
                  console.log("逆解析地址成功")
                  let formatAddress = res.result.formatted_addresses.recommend
                  that.place = encodeURIComponent(formatAddress)
                  console.log(formatAddress, that.place)
                  console.log("距离工作室:", that.distance)
                  console.log("当前半径:", that.radius)
                }
              })
              if (that.distance <= that.radius) {
                that.success = true
                uni.request({
                  url: that.$globalUrl + "/sign/onDutySign",
                  method: "GET",
                  data: {
                    "type": 1,
                    "place": that.success,
                    "success": that.success
                  },
                  header: {
                    "Authorization": uni.getStorageSync('tokenHead') + ' ' + uni.getStorageSync('token')
                  },
                  success(res) {
                    console.log(res)
                    that.isSigned = true
                    if (that.isSigned) {
                      uni.showToast({
                        icon: 'error',
                        title: '请勿重复签到',
                        duration: 1500
                      })
                    }
                    if (res.data.code === 401) {
                      uni.showToast({
                        icon: "error",
                        title: '请先登录再定位',
                        duration: 2000
                      })
                    }
                    if (res.data.code === 200) {
                      uni.showToast({
                        icon: "success",
                        title: "签到成功",
                        duration: 2000
                      })
                    }
                    if (res.data.code === 500) {
                      uni.showToast({
                        icon: "error",
                        title: "未到签到时间",
                        duration: 2000
                      })
                    }
                  }
                })
              } else {
                uni.showToast({
                  icon: "error",
                  title: "不在范围之内",
                  duration: 2000
                })
              }
            }
          })
        }
      },
      // 计算当前定位距离工作室的距离
      calculateDistance(lat1, lon1, lat2, lon2) {
        function rad(d) {
          return d * Math.PI / 180.0
        }
        const radLat1 = rad(lat1)
        const radLat2 = rad(lat2)
        const a = radLat1 - radLat2
        const b = rad(lon1) - rad(lon2)
        let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
          Math.sin(b / 2), 2)))
        s *= 6378.137
        console.log("s的值=>", s)
        // s输出为米
        s = Math.round(s * 100)
        s = s.toFixed(1)
        return s
      },
      onDuty() {
        let that = this
        // 用户点击签到按钮的时间
        that.userSignTime = new Date(formatTime(new Date())).getTime()
        // 判断手机设置有没有打开WiFi开关
        wx.getSystemInfo({
          success(res) {
            console.log(res.wifiEnabled)
            that.isOpenMobileWifi = res.wifiEnabled
            if (!that.isOpenMobileWifi) {
              uni.showToast({
                icon: "error",
                title: "请打开WiFi开关",
                duration: 2000
              })
            } else {
              let SSID = "RococoStudio"
              let BSSID = "f0:b4:29:e0:1d:ad"
              console.log("进行值日签到")
              // 获取网络类型
              wx.getNetworkType({
                success(res) {
                  console.log(res)
                  if (res.networkType !== "wifi") {
                    uni.showToast({
                      icon: "error",
                      title: "请连接工作室WiFi",
                      duration: 2000
                    })
                  } else {
                    // 初始化WiFi模块
                    wx.startWifi({
                      success() {
                        // 判断是不是工作室的WiFi
                        wx.getConnectedWifi({
                          success(res) {
                            // 值班签到
                            if (res.wifi.SSID === SSID && res.wifi.BSSID === BSSID && that.userSignTime <= that.signInEndTime && that.userSignTime >= that.signInBeginTime) {
                              that.isSuccess = true
                              uni.request({
                                url: 'https://www.lingche.net.cn:9223/sign/onDutySign',
                                method: 'GET',
                                header: {
                                  "Authorization": uni.getStorageSync('tokenHead') + ' ' + uni.getStorageSync('token')
                                },
                                data: {
                                  place: that.isSuccess,
                                  success: that.isSuccess,
                                  type: 2
                                },
                                success(res) {
                                  console.log(res)
                                  if (res.data.code === 200) {
                                    uni.showToast({
                                      icon: 'success',
                                      title: "签到成功",
                                      duration: 2000
                                    })
                                  }
                                  if (res.data.code === 401) {
                                    uni.showToast({
                                      icon: 'error',
                                      title: "请先登录",
                                      duration: 2000
                                    })
                                  }
                                  if (res.data.code === 500) {
                                    uni.showToast({
                                      icon: 'error',
                                      title: "本周不是你值班",
                                      duration: 2000
                                    })
                                  }
                                }
                              })
                            } else if (res.wifi.SSID !== SSID || res.wifi.BSSID !== BSSID) {
                              uni.showToast({
                                icon: 'error',
                                title: '请连接工作室WiFi'
                              })
                            } else if (that.userSignTime < that.signInBeginTime) {
                              uni.showToast({
                                icon: 'error',
                                title: '还未到值班时间',
                                duration: 2000
                              })
                            } else if (that.userSignTime > that.signInEndTime) {
                              uni.showToast({
                                icon: 'error',
                                title: '签到时间已过',
                                duration: 2000
                              })
                            } else {
                              // 值班签退, 20:30之后都能签退
                              if (that.userSignTime > that.signOutTime && that.userSignTime <= that.signOutEndTime) {
                                that.isSignOut = true
                                uni.request({
                                  url: that.serverUrl + '/sign/signOut',
                                  method: 'PUT',
                                  header: {
                                    "Authorization": uni.getStorageSync('tokenHead') + ' ' + uni.getStorageSync('token')
                                  },
                                  data: {
                                    success: that.isSignOut,
                                    type: 2
                                  },
                                  success(res) {
                                    console.log(res)
                                    if (res.data.code === 200) {
                                      uni.showToast({
                                        icon: 'success',
                                        title: '签退成功',
                                        duration: 2000
                                      })
                                    }
                                  }
                                })
                              } else {
                                uni.showToast({
                                  icon: 'error',
                                  title: '20:30之后才能签退',
                                  duration: 2000
                                })
                              }
                            }
                          }
                        })
                      }
                    })
                  }
                }
              })
            }
          }
        })
      }
    },
    onLoad() {
      let prefixTime = formatPrefixTime(new Date())
      // 规定的每日签到开始时间
      this.signInBeginTime = new Date(prefixTime + ' ' + '19:00:00').getTime()
      // 规定的每日签到结束时间
      this.signInEndTime = new Date(prefixTime + ' ' + '19:30:00').getTime()
      // 规定的每日签退开始时间
      this.signOutTime = new Date(prefixTime + ' ' + '20:30:00').getTime()
      // 规定的每日签退结束时间
      this.signOutEndTime = new Date(prefixTime + ' ' + '23:59:59').getTime()
      // 规定的每周会议开始签到时间
      this.meetingBeginTime = new Date(prefixTime + ' ' + '12:40').getTime()
      // 规定的每周会议结束签到时间
      this.meetingEndTime = new Date(prefixTime + ' ' + '12:50').getTime()
    }
  }
</script>

<style>
  .ImageBox {
    width: 100%;
    height: 100%;
    background: '#F6F6F6'
  }

  .topImage {
    width: 500px;
    height: 300px;
    margin: 0 auto;
  }

  .upload,
  .locationBox,
  .MemberBox {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    width: 95%;
    height: 100px;
    margin: 10px auto;
    background-color: #FFFFFF;
    border-radius: 30px;
  }

  .img1 {
    width: 110px;
    height: 90px;
    margin: 10px;
    border-radius: 30px;
  }
  
  .textBox {
    flex: 1;
    width: 50%;
    margin-left: 20px;
  }

  .topText {
    font-size: 20px;
    color: #242424;
  }

  .bottomText {
    font-size: 12px;
    color: #242424;
  }
</style>
